<template>
  <Layout>
    <div class="billing-container">
      <!-- 账单筛选和查询区域 -->
      <el-card class="filter-card">
        <template #header>
          <div class="card-header">
            <h3>账单查询</h3>
            <div class="refresh-section">
              <span class="update-time">更新时间: {{ formatTime(lastUpdateTime) }}</span>
              <el-button :icon="Refresh" circle size="small" @click="refreshData"
                         :loading="loading"></el-button>
            </div>
          </div>
        </template>

        <div class="filter-form">
          <el-form :model="filterForm" inline>
            <el-form-item label="交易类型">
              <el-select v-model="filterForm.tradeType" placeholder="全部类型" clearable>
                <el-option label="全部" value=""></el-option>
                <el-option label="充值" :value="1"></el-option>
                <el-option label="提现" :value="2"></el-option>
                <el-option label="转账" :value="3"></el-option>
                <el-option label="支付" :value="4"></el-option>
                <el-option label="退款" :value="5"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="交易状态">
              <el-select v-model="filterForm.status" placeholder="全部状态" clearable>
                <el-option label="全部" value=""></el-option>
                <el-option label="处理中" :value="0"></el-option>
                <el-option label="成功" :value="1"></el-option>
                <el-option label="失败" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="交易时间">
              <el-date-picker
                v-model="filterForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="resetFilter">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>

      <!-- 账单统计信息 -->
      <el-card class="statistics-card">
        <template #header>
          <div class="card-header">
            <h3>本月账单统计</h3>
          </div>
        </template>

        <div class="statistics-container">
          <div class="statistic-item">
            <div class="statistic-title">总收入</div>
            <div class="statistic-value income">+{{ formatAmount(monthlyStats.totalIncome) }}</div>
          </div>
          <div class="statistic-item">
            <div class="statistic-title">总支出</div>
            <div class="statistic-value expense">-{{ formatAmount(monthlyStats.totalExpense) }}</div>
          </div>
          <div class="statistic-item">
            <div class="statistic-title">交易笔数</div>
            <div class="statistic-value">{{ monthlyStats.transactionCount }}</div>
          </div>
          <div class="statistic-item">
            <div class="statistic-title">净收入</div>
            <div class="statistic-value" :class="monthlyStats.netIncome >= 0 ? 'income' : 'expense'">
              {{ monthlyStats.netIncome >= 0 ? '+' : '-' }}{{ formatAmount(Math.abs(monthlyStats.netIncome)) }}
            </div>
          </div>
        </div>

        <div class="chart-container" v-if="monthlyStats.transactionCount > 0">
          <div ref="incomeExpenseChartRef" class="income-expense-chart"></div>
        </div>
      </el-card>

      <!-- 账单明细 -->
      <el-card class="transactions-card">
        <template #header>
          <div class="card-header">
            <h3>账单明细</h3>
            <div class="export-section">
              <el-button size="small" @click="exportBilling">
                <el-icon><Download /></el-icon>
                导出账单
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          :data="transactions"
          border
          stripe
          style="width: 100%"
          :row-class-name="tableRowClassName"
          v-loading="tableLoading"
          @row-click="showTransactionDetail"
        >
          <el-table-column prop="tradeNo" label="交易流水号" min-width="180"></el-table-column>
          <el-table-column prop="tradeTypeName" label="交易类型" width="100">
            <template #default="scope">
              <el-tag :type="getTradeTypeTagType(scope.row.tradeType)" size="small">
                {{ scope.row.tradeTypeName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额" width="150">
            <template #default="scope">
              <span :class="{'income': isIncome(scope.row), 'expense': !isIncome(scope.row)}">
                {{ isIncome(scope.row) ? '+' : '-' }} {{ formatAmount(Math.abs(scope.row.amount)) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="balance" label="账户余额" width="150">
            <template #default="scope">
              {{ formatAmount(scope.row.balance) }}
            </template>
          </el-table-column>
          <el-table-column prop="statusName" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)" size="small">
                {{ scope.row.statusName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="channelName" label="渠道" width="120"></el-table-column>
          <el-table-column prop="createTime" label="交易时间" min-width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150">
            <template #default="scope">
              <el-tooltip v-if="scope.row.remark && scope.row.remark.length > 20" 
                          :content="scope.row.remark" 
                          placement="top-start" 
                          effect="light">
                <span>{{ scope.row.remark.substring(0, 20) }}...</span>
              </el-tooltip>
              <span v-else>{{ scope.row.remark || '-' }}</span>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalTransactions"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </el-card>
    </div>

    <!-- 交易详情对话框 -->
    <el-dialog v-model="transactionDetailVisible" title="交易详情" width="500px">
      <div v-if="currentTransaction" class="transaction-detail">
        <div class="transaction-header">
          <el-tag :type="getTradeTypeTagType(currentTransaction.tradeType)" class="transaction-type">
            {{ currentTransaction.tradeTypeName }}
          </el-tag>
          <div class="transaction-amount" :class="{'income': isIncome(currentTransaction),
          'expense': !isIncome(currentTransaction)}">
            {{ isIncome(currentTransaction) ? '+' : '-' }} {{ formatAmount(Math.abs(currentTransaction.amount)) }}
          </div>
        </div>

        <el-divider></el-divider>

        <div class="detail-item">
          <span class="detail-label">交易流水号</span>
          <span class="detail-value">{{ currentTransaction.tradeNo }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">交易状态</span>
          <el-tag :type="getStatusTagType(currentTransaction.status)">{{ currentTransaction.statusName }}</el-tag>
        </div>
        <div class="detail-item">
          <span class="detail-label">交易时间</span>
          <span class="detail-value">{{ formatDateTime(currentTransaction.createTime) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">交易渠道</span>
          <span class="detail-value">{{ currentTransaction.channelName }}</span>
        </div>
        <div class="detail-item" v-if="currentTransaction.targetAccount">
          <span class="detail-label">目标账户</span>
          <span class="detail-value">{{ currentTransaction.targetAccount }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">交易后余额</span>
          <span class="detail-value">{{ formatAmount(currentTransaction.balance) }}</span>
        </div>
        <div class="detail-item" v-if="currentTransaction.remark">
          <span class="detail-label">备注</span>
          <span class="detail-value">{{ currentTransaction.remark }}</span>
        </div>
      </div>
    </el-dialog>
  </Layout>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Download } from '@element-plus/icons-vue';
import Layout from '@/components/layout/Layout.vue';
import { getTransactionList, getTransactionDetail } from '@/api/transaction';
import * as echarts from 'echarts/core';
import { BarChart, PieChart } from 'echarts/charts';
import {
  TitleComponent, TooltipComponent, LegendComponent,
  GridComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册 ECharts 组件
echarts.use([
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  CanvasRenderer
]);

// 筛选表单数据
const filterForm = reactive({
  tradeType: '',
  status: '',
  dateRange: []
});

// 分页数据
const currentPage = ref(1);
const pageSize = ref(10);
const totalTransactions = ref(0);

// 账单数据
const transactions = ref([]);
const loading = ref(false);
const tableLoading = ref(false);
const lastUpdateTime = ref(new Date());

// 交易详情数据
const currentTransaction = ref(null);
const transactionDetailVisible = ref(false);

// 图表实例
const incomeExpenseChartRef = ref(null);
let incomeExpenseChart = null;

// 月度统计数据
const monthlyStats = reactive({
  totalIncome: 0,
  totalExpense: 0,
  transactionCount: 0,
  netIncome: 0
});

// 初始化
onMounted(async () => {
  await refreshData();
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize);
});

// 在组件卸载时移除监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  
  // 销毁图表实例
  if (incomeExpenseChart) {
    incomeExpenseChart.dispose();
    incomeExpenseChart = null;
  }
});

// 处理窗口大小变化
const handleResize = () => {
  if (incomeExpenseChart) {
    incomeExpenseChart.resize();
  }
};

// 查询账单列表
const fetchTransactions = async () => {
  tableLoading.value = true;
  try {
    // 构建参数
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    };

    // 添加交易类型过滤
    if (filterForm.tradeType) {
      params.tradeType = filterForm.tradeType;
    }

    // 添加交易状态过滤
    if (filterForm.status !== '') {
      params.status = filterForm.status;
    }

    // 添加日期范围过滤
    if (filterForm.dateRange && filterForm.dateRange.length === 2) {
      params.startTime = `${filterForm.dateRange[0]} 00:00:00`;
      params.endTime = `${filterForm.dateRange[1]} 23:59:59`;
    }

    const response = await getTransactionList(params);
    if (response.code === 0) {
      transactions.value = response.data || [];
      totalTransactions.value = response.total || 0;
      lastUpdateTime.value = new Date();
    }
  } catch (error) {
    console.error('获取账单列表失败:', error);
    ElMessage.error('获取账单列表失败，请刷新重试');
  } finally {
    tableLoading.value = false;
  }
};

// 计算月度统计数据
const calculateMonthlyStats = async () => {
  try {
    // 获取当前月份的第一天和最后一天
    const now = new Date();
    const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
    const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
    
    const firstDayStr = formatDateForRequest(firstDay);
    const lastDayStr = formatDateForRequest(lastDay);

    // 查询本月所有交易记录（不分页，获取所有数据进行统计）
    const params = {
      pageNum: 1,
      pageSize: 1000, // 假设不会超过1000条
      startTime: `${firstDayStr} 00:00:00`,
      endTime: `${lastDayStr} 23:59:59`
    };

    const response = await getTransactionList(params);
    if (response.code === 0) {
      const monthlyTransactions = response.data || [];
      
      // 重置统计数据
      monthlyStats.totalIncome = 0;
      monthlyStats.totalExpense = 0;
      monthlyStats.transactionCount = monthlyTransactions.length;
      
      // 计算收入和支出
      monthlyTransactions.forEach(transaction => {
        if (transaction.status === 1) { // 只统计成功的交易
          if (isIncome({ tradeType: transaction.tradeType })) {
            monthlyStats.totalIncome += parseFloat(transaction.amount);
          } else {
            monthlyStats.totalExpense += parseFloat(transaction.amount);
          }
        }
      });
      
      // 计算净收入
      monthlyStats.netIncome = monthlyStats.totalIncome - monthlyStats.totalExpense;
      
      // 更新统计图表
      nextTick(() => {
        initIncomeExpenseChart();
      });
    }
  } catch (error) {
    console.error('计算月度统计数据失败:', error);
    ElMessage.error('计算月度统计数据失败，请刷新重试');
  }
};

// 格式化日期为请求参数格式
const formatDateForRequest = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 查询交易详情
const fetchTransactionDetail = async (tradeNo) => {
  try {
    const response = await getTransactionDetail(tradeNo);
    if (response.code === 0) {
      currentTransaction.value = response.data;
      transactionDetailVisible.value = true;
    }
  } catch (error) {
    console.error('获取交易详情失败:', error);
    ElMessage.error('获取交易详情失败，请重试');
  }
};

// 初始化收入支出统计图表
const initIncomeExpenseChart = () => {
  if (!incomeExpenseChartRef.value) return;
  
  if (incomeExpenseChart) {
    incomeExpenseChart.dispose();
  }
  
  incomeExpenseChart = echarts.init(incomeExpenseChartRef.value);
  
  const option = {
    title: {
      text: '本月收支情况',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c}'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['收入', '支出', '净收入']
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value) => {
          return formatAmount(value);
        }
      }
    },
    series: [
      {
        data: [
          {
            value: monthlyStats.totalIncome,
            itemStyle: { color: '#67C23A' }
          },
          {
            value: monthlyStats.totalExpense,
            itemStyle: { color: '#F56C6C' }
          },
          {
            value: monthlyStats.netIncome,
            itemStyle: { color: monthlyStats.netIncome >= 0 ? '#409EFF' : '#E6A23C' }
          }
        ],
        type: 'bar',
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)'
        },
        label: {
          show: true,
          position: 'top',
          formatter: (params) => {
            return formatAmount(params.value);
          }
        }
      }
    ]
  };
  
  incomeExpenseChart.setOption(option);
};

// 刷新数据
const refreshData = async () => {
  loading.value = true;
  try {
    await Promise.all([
      fetchTransactions(),
      calculateMonthlyStats()
    ]);
    ElMessage.success('数据已刷新');
  } catch (error) {
    console.error('刷新数据失败:', error);
    ElMessage.error('刷新数据失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 处理查询
const handleSearch = () => {
  currentPage.value = 1;
  fetchTransactions();
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.tradeType = '';
  filterForm.status = '';
  filterForm.dateRange = [];
  handleSearch();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchTransactions();
};

// 处理每页记录数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchTransactions();
};

// 显示交易详情
const showTransactionDetail = (row) => {
  fetchTransactionDetail(row.tradeNo);
};

// 导出账单
const exportBilling = async () => {
  // 先询问用户导出格式偏好
  await ElMessageBox.confirm(
    '请选择导出格式',
    '导出账单',
    {
      confirmButtonText: 'Excel',
      cancelButtonText: 'CSV',
      distinguishCancelAndClose: true,
      type: 'info'
    }
  ).then(async () => {
    // 用户选择了Excel
    await doExport('excel');
  }).catch((action) => {
    if (action === 'cancel') {
      // 用户选择了CSV
      doExport('csv');
    }
  });
};

// 执行导出操作
const doExport = async (format) => {
  try {
    // 构建参数
    const params = {
      format: format
    };

    // 添加交易类型过滤
    if (filterForm.tradeType) {
      params.tradeType = filterForm.tradeType;
    }
    
    // 添加交易状态过滤
    if (filterForm.status !== '') {
      params.status = filterForm.status;
    }

    // 添加日期范围过滤
    if (filterForm.dateRange && filterForm.dateRange.length === 2) {
      params.startTime = `${filterForm.dateRange[0]} 00:00:00`;
      params.endTime = `${filterForm.dateRange[1]} 23:59:59`;
    }
    
    loading.value = true;
    
    // 使用Axios直接下载文件
    // 修改请求方式，通过window.location.href直接下载
    // 构建查询参数字符串
    const queryParams = new URLSearchParams();
    for (let key in params) {
      queryParams.append(key, params[key]);
    }
    
    // 补充token到Cookie，保证后端验证通过
    const token = document.cookie.replace(/(?:(?:^|.*;\s*)virtual_bank_token\s*=\s*([^;]*).*$)|^.*$/, "$1") || 
                document.cookie.replace(/(?:(?:^|.*;\s*)token\s*=\s*([^;]*).*$)|^.*$/, "$1");
    if (token) {
      // 确保Cookie中有token
      if (!document.cookie.includes('virtual_bank_token') && !document.cookie.includes('token=')) {
        document.cookie = `token=${token}; path=/`;
      }
    }
    
    // 构建下载链接
    const downloadUrl = `${window.location.origin}/api/transaction/export?${queryParams.toString()}`;
    
    // 创建一个隐藏的iframe来处理文件下载
    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    iframe.src = downloadUrl;
    document.body.appendChild(iframe);
    
    // 设置超时，如果下载未开始，去掉loading状态
    setTimeout(() => {
      loading.value = false;
      // 5秒后移除iframe
      setTimeout(() => {
        if (document.body.contains(iframe)) {
          document.body.removeChild(iframe);
        }
      }, 5000);
    }, 2000);
    
    ElMessage.success('文件已开始下载');
  } catch (error) {
    console.error('导出账单失败:', error);
    ElMessage.error('导出账单失败，请重试');
    loading.value = false;
  }
};

// 判断交易类型是否为收入
const isIncome = (transaction) => {
  // 充值和退款是收入
  return transaction.tradeType === 1 || transaction.tradeType === 5;
};

// 表格行样式
const tableRowClassName = ({ row }) => {
  if (row.status === 2) {
    return 'failed-row';
  } else if (row.status === 0) {
    return 'processing-row';
  }
  return '';
};

// 获取交易类型对应的标签类型
const getTradeTypeTagType = (tradeType) => {
  const typeMap = {
    1: 'success', // 充值
    2: 'warning', // 提现
    3: 'info',    // 转账
    4: 'danger',  // 支付
    5: 'success'  // 退款
  };

  return typeMap[tradeType] || 'info';
};

// 获取交易状态对应的标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    0: 'info',    // 处理中
    1: 'success', // 成功
    2: 'danger'   // 失败
  };

  return statusMap[status] || 'info';
};

// 格式化金额
const formatAmount = (amount) => {
  if (amount === undefined || amount === null) return '0.00';
  return parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 格式化时间
const formatTime = (dateTime) => {
  if (!dateTime) return '暂无数据';

  const date = new Date(dateTime);
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${hours}:${minutes}:${seconds}`;
};

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '暂无数据';
  
  const date = new Date(dateTimeStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
</script>

<style scoped>
.billing-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.refresh-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.update-time {
  font-size: 14px;
  color: #909399;
}

.filter-form {
  margin-top: 10px;
}

.statistics-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.statistic-item {
  flex: 1;
  min-width: 200px;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.statistic-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.statistic-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.chart-container {
  margin-top: 20px;
}

.income-expense-chart {
  width: 100%;
  height: 300px;
}

.income {
  color: #67c23a;
}

.expense {
  color: #f56c6c;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.transaction-detail {
  padding: 10px;
}

.transaction-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.transaction-type {
  font-size: 16px;
}

.transaction-amount {
  font-size: 24px;
  font-weight: 700;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.detail-label {
  color: #909399;
  font-size: 14px;
}

.detail-value {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

/* 表格行样式 */
:deep(.failed-row) {
  background-color: #fef0f0;
}

:deep(.processing-row) {
  background-color: #f5f7fa;
}

@media (max-width: 768px) {
  .statistics-container {
    flex-direction: column;
  }
  
  .filter-form .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
    width: 100%;
  }
}
</style>
